#include "CBuilding.h"
#include "CRandom.h"


CBuilding::CBuilding(IrrlichtDevice* device, u32 buildingsNumber)
{
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	
	cubeSize	= 32.f;
	line		= 0;
	lastLine	= 0;
	position	= vector3df(0.f, cubeSize/2, cubeSize*2);

	// Initialize RNG
	CRandom::setSeed();

	// Buildings
	for (u32 i = 0; i < buildingsNumber; ++i)
	{
		buildingNode.push_back(smgr->addCubeSceneNode(cubeSize));

		if (buildingNode[i])
		{
			buildingNode[i]->setPosition(genPosition());

			buildingNode[i]->setMaterialTexture(0,
				driver->getTexture("data/textures/building/building.jpg"));

			buildingNode[i]->setMaterialFlag(EMF_LIGHTING, false);

			buildingNode[i]->setTriangleSelector(
				smgr->createTriangleSelectorFromBoundingBox(buildingNode[i]));
		}
	}
}


CBuilding::~CBuilding(void)
{
}


ISceneNode* CBuilding::getNode(u32 index)
{
	return buildingNode[index];
}


/*
* Returns building position acording to the next rules:
* - buildings are placed on the road on 3 imaginary lines;
* - position of the building is within his line;
* - there are no two buildings in the row on the same line.
*/
vector3df CBuilding::genPosition(void)
{
	while (line == lastLine)
	{
		line = CRandom::getNumber(1, 3);
	}
	
	position.X = line * 32 + CRandom::getNumber(-cubeSize/4, cubeSize/4);

	lastLine = line;

	position.Z += CRandom::getNumber(cubeSize*3/2, cubeSize*2);

	return position;
}